package com.zqc.login.controller;

import com.zqc.login.pojo.User;
import com.zqc.login.service.UserService;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;

@RestController
@RequestMapping("/api/user")
public class UserController {
    @Reference
    private UserService userService;

    @GetMapping("/register/{email}/{password}/{code}")
    public Boolean register(
            @PathVariable(value = "email") String email,
            @PathVariable(value = "password") String password,
            @PathVariable(value = "code") String code) {
        return userService.register(email, password, code);
    }

    @GetMapping("/isRegistered/{email}")
    public Boolean isRegistered(@PathVariable(value = "email") String email) {
        return userService.isRegistered(email);
    }

    @GetMapping("/login/{email}/{password}")
    public String login(
            @PathVariable(value = "email") String email,
            @PathVariable(value = "password") String password,
            HttpServletResponse response) {
        User user = userService.login(email, password);
        if (user != null) {
            Cookie cookie = new Cookie("token", user.getToken());
            cookie.setMaxAge(60 * 10);
            cookie.setPath("/");
            response.addCookie(cookie);
            return user.getEmail();
        }
        return null;
    }

    @GetMapping("/info/{token}")
    public String info(@PathVariable(value = "token") String token) {
        return userService.getEmailByToken(token);
    }
}

